<?php
if (page::$ajax) {

} else {
  $tmp = new Template('pan_mods');
  $refresh = false;

  // Get list of installed modules
  $sql_all = "SELECT * FROM `mods` ORDER BY `mod`";
  $mod = db::q($sql_all);
  $installed = $mod->exists() ? $mod->arr('mod') : array();

  // Lookup changes in install modules
  while ($mod->next()->exists()) {

    if (!mod::check_filesystem($mod->mod)) {
      // Module not found on disk
      db::delete('mods', $mod->id);
      $refresh = true;

    } elseif (!empty($_POST['mod_enable']) && $mod->enabled != isset($_POST['en_' . $mod->mod])) {
      // received command to switch enabled status
      mod::toggle_enabled($mod->mod);
      $refresh = true;
    }
  }

  // Check for new modules and install
  $dir = 'mod/';
  foreach (scandir($dir, 1) as $item) {
    if (!in_array($item, $installed) && mod::check_filesystem($item)) {
      $name = ''; $descr = ''; $version = '';
      include $dir . $item . '/about.php';
      $q = "INSERT INTO `mods` ( `mod`, `name`, `descr`, `version` ) VALUES ( '::1', '::2', '::3', '::4' )";
      db::q($q, $item, $name, $descr, $version);
      $refresh = true;
    }
  }

  if ($refresh) {
    $mod = db::q($sql_all);
  } else {
    $mod->initial();
  }
  
  $tmp->assign('mod', $mod);
  page::$html->assign('content', $tmp);
}
